use regex::Regex;

// extract_pattern_value(r"Total accesses: (\d+)", text)
#[inline]
pub fn extract_data(pattern: &str, text: &str) -> String {
    extract_with_position(pattern, text, 1)
}

#[inline]
pub fn extract_from_multi_patterns(pattern_position_list: &[(&str, usize)], text: &str) -> String {
    for (pattern, position) in pattern_position_list {
        let result = extract_with_position(pattern, text, *position);
        if !result.is_empty() {
            return result;
        }
    }
    "".to_owned()
}

#[inline]
pub fn extract_with_position(pattern: &str, text: &str, position: usize) -> String {
    let re = build_regex(pattern);
    if let Some(caps) = re.captures(text) {
        caps[position].to_owned()
    } else {
        tracing::debug!("{pattern} maybe error");
        "".to_owned()
    }
}

#[inline]
pub fn extract_combined_index(prefix: &str, index: &str, after: &str, text: &str) -> String {
    extract_data((prefix.to_owned() + index + after).as_str(), text)
}

pub fn exists_value_from_vec(values: Vec<String>) -> String {
    for value in values {
        if !value.is_empty() {
            return value;
        }
    }
    "".to_owned()
}

pub fn get_sys_uptime(value: &str) -> f64 {
    extract_data(r".3.6.1.2.1.1.3.0 = Timeticks: \((\d+)\) ", value)
        .parse::<f64>()
        .unwrap_or(1.0)
}

pub fn build_regex(pattern: &str) -> Regex {
    Regex::new(pattern).unwrap()
}
